package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 508. 出现次数最多的子树元素和
 *
 * @Author liw
 * @Date 2021/5/10 17:01
 * @Version 1.0
 */
public class FindFrequentTreeSum {

    public static void main(String[] args) {
        FindFrequentTreeSum test = new FindFrequentTreeSum();

        int[] frequentTreeSum = test.findFrequentTreeSum(TreeNode.getInstance3());

    }


    public int[] findFrequentTreeSum(TreeNode root) {
        Map<Integer, Integer> map = new HashMap<>();
        find(root, map);
        int max = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            max = Math.max(max, entry.getValue());
        }
        List<Integer> collect = new ArrayList<>();

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == max) {
                collect.add(entry.getKey());
            }
        }
        int size = collect.size();
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) {
            arr[i] = collect.get(i);
        }
        return arr;
    }

    private int find(TreeNode root, Map<Integer, Integer> map) {
        if (root == null) {
            return 0;
        }
        int l = find(root.left, map);
        int r = find(root.right, map);
        int value = root.val + l + r;
        map.merge(value, 1, (a, b) -> a + b);
        return value;
    }
}
